package com.example.boot_6.map;

import java.util.*;
import java.util.stream.IntStream;

public class Map_1 {

    public static Map<String, List<Integer>> getElementPositions1(List<String> list) {
        Map<String, List<Integer>> positionsMap = new HashMap<>();
        IntStream.range(0,list.size()).forEach(i ->{
           String str = list.get(i);
            positionsMap.putIfAbsent(str, new ArrayList<>());
            positionsMap.get(str).add(i);
        });
        return positionsMap;
    }


    public static Map<String, List<Integer>> getElementPositions(List<String> list) {
        Map<String, List<Integer>> positionsMap = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i);
            List<Integer> positions = positionsMap.get(str);

            if (positions == null) { // 如果 positionsMap 还不存在 str 这个键及其对应的 List<Integer>
                positions = new ArrayList<>(1);
                positionsMap.put(str, positions); // 将 str 及其对应的 positions 放入 positionsMap
            }

            positions.add(i); // 将索引加入 str 相关联的 List<Integer> 中
        }

        return positionsMap;
    }

    public static void main(String[] args) throws Exception {
        List<String> list = Arrays.asList("a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g");

        list.stream().distinct().forEach(System.out::println);
        System.out.println(list);
        System.out.println("使用 Java8 之前的 API：");
        Map<String, List<Integer>> elementPositions = getElementPositions1(list);
        System.out.println(elementPositions);





    }
}
